<template>
  <div class="bills">
    <div class="head-con">
      <!-- 业务类型选择 -->
      <div class="searchDiv">
        <label class="label_input">
          <span style="color: red">*</span>业务类型:
        </label>
        <el-select
          v-model="WriteoffType"
          style="width: 150px"
          clearable
          @change="handleWriteoffTypeChange"
        >
          <el-option label="预收冲应收" value="yscys" />
          <el-option label="预付冲应付" value="yfcyf" />
          <el-option label="应收冲应付" value="yscyf" />
          <el-option label="应收转应收" value="yszys" />
          <el-option label="应付转应付" value="yfzyf" />
        </el-select>
      </div>

      <!-- 动态区域 -->
      <!-- 预收冲应收 -->
      <template v-if="WriteoffType === 'yscys'">
        <div class="searchDiv">
          <label class="label_input"
            ><span style="color: red">*</span>客户:</label
          >
          <el-input 
            v-model="customerForm.customerName" 
            placeholder="点击选择客户"
            @click="openCustomerDialog" 
            readonly 
            style="width: 200px;" 
          />
        </div>
        <div class="searchDiv">
          <label class="label_input">业务员:</label>
          <el-select
            v-model="Firstresponsible"
            style="width: 130px"
            placeholder="请选择"
          >
            <el-option
              v-for="item in responsibleOptions"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            />
          </el-select>
        </div>
      </template>

      <!-- 预付冲应付 -->
      <template v-else-if="WriteoffType === 'yfcyf'">
        <div class="searchDiv">
          <label class="label_input"
            ><span style="color: red">*</span>供应商:</label
          >
          <el-input
            v-model="form.supplier_name"
            style="width: 220px"
            placeholder="选择供应商(必选)"
            clearable
          >
            <template #append>
              <el-button :icon="Search" @click="supplierDialog.open()" />
            </template>
          </el-input>
        </div>
        <div class="searchDiv">
          <label class="label_input">业务员:</label>
          <el-select
            v-model="Firstresponsible"
            style="width: 130px"
            placeholder="请选择"
          >
            <el-option
              v-for="item in responsibleOptions"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            />
          </el-select>
        </div>
      </template>

      <!-- 应收冲应付 -->
      <template v-else-if="WriteoffType === 'yscyf'">
        <div class="searchDiv">
          <label class="label_input"
            ><span style="color: red">*</span>客户:</label
          >
          <el-input 
            v-model="customerForm.customerName" 
            placeholder="点击选择客户"
            @click="openCustomerDialog" 
            readonly 
            style="width: 200px;" 
          />
        </div>
        <div class="searchDiv">
          <label class="label_input"
            ><span style="color: red">*</span>供应商:</label
          >
          <el-input
            v-model="form.supplier_name"
            style="width: 220px"
            placeholder="选择供应商(必选)"
            clearable
          >
            <template #append>
              <el-button :icon="Search" @click="supplierDialog.open()" />
            </template>
          </el-input>
        </div>
        <div class="searchDiv">
          <label class="label_input">客户业务员:</label>
          <el-select
            v-model="Firstresponsible"
            style="width: 130px"
            placeholder="请选择"
          >
            <el-option
              v-for="item in responsibleOptions"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            />
          </el-select>
        </div>
        <div class="searchDiv">
          <label class="label_input">供应商业务员:</label>
          <el-select
            v-model="Secondresponsible"
            style="width: 130px"
            placeholder="请选择"
          >
            <el-option
              v-for="item in responsibleOptions"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            />
          </el-select>
        </div>
      </template>

      <!-- 应收转应收 -->
      <template v-else-if="WriteoffType === 'yszys'">
        <div class="searchDiv">
          <label class="label_input"
            ><span style="color: red">*</span>转出客户:</label
          >
          <el-input 
            v-model="fromCustomerForm.customerName" 
            placeholder="点击选择转出客户"
            @click="() => openCustomerDialog('from')" 
            readonly 
            style="width: 200px;" 
          />
        </div>
        <div class="searchDiv">
          <label class="label_input"
            ><span style="color: red">*</span>转入客户:</label
          >
          <el-input 
            v-model="toCustomerForm.customerName" 
            placeholder="点击选择转入客户"
            @click="() => openCustomerDialog('to')" 
            readonly 
            style="width: 200px;" 
          />
        </div>
        <div class="searchDiv">
          <label class="label_input">转出业务员:</label>
          <el-select
            v-model="Firstresponsible"
            style="width: 130px"
            placeholder="请选择"
          >
            <el-option
              v-for="item in responsibleOptions"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            />
          </el-select>
        </div>
        <div class="searchDiv">
          <label class="label_input">转入业务员:</label>
          <el-select
            v-model="Secondresponsible"
            style="width: 130px"
            placeholder="请选择"
          >
            <el-option
              v-for="item in responsibleOptions"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            />
          </el-select>
        </div>
      </template>

      <!-- 应付转应付 -->
      <template v-else-if="WriteoffType === 'yfzyf'">
        <div class="searchDiv">
          <label class="label_input"
            ><span style="color: red">*</span>转出供应商:</label
          >
          <el-input
            v-model="fromSupplierForm.supplier_name"
            style="width: 220px"
            placeholder="选择转出供应商(必选)"
            clearable
          >
            <template #append>
              <el-button :icon="Search" @click="() => openSupplierDialog('from')" />
            </template>
          </el-input>
        </div>
        <div class="searchDiv">
          <label class="label_input"
            ><span style="color: red">*</span>转入供应商:</label
          >
          <el-input
            v-model="toSupplierForm.supplier_name"
            style="width: 220px"
            placeholder="选择转入供应商(必选)"
            clearable
          >
            <template #append>
              <el-button :icon="Search" @click="() => openSupplierDialog('to')" />
            </template>
          </el-input>
        </div>
        <div class="searchDiv">
          <label class="label_input">转出业务员:</label>
          <el-select
            v-model="Firstresponsible"
            style="width: 130px"
            placeholder="请选择"
          >
            <el-option
              v-for="item in responsibleOptions"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            />
          </el-select>
        </div>
        <div class="searchDiv">
          <label class="label_input">转入业务员:</label>
          <el-select
            v-model="Secondresponsible"
            style="width: 130px"
            placeholder="请选择"
          >
            <el-option
              v-for="item in responsibleOptions"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            />
          </el-select>
        </div>
      </template>

      <!-- 公共字段 -->
      <div class="searchDiv">
        <label class="label_input">单据日期:</label>
        <el-date-picker v-model="date" type="date" style="width: 150px" />
      </div>
      <div class="searchDiv">
        <label class="label_input">单据编号:</label>
        <span v-if="!editingBillNo" @click="editBillNo" class="bill-no">{{
          billNo
        }}</span>
        <el-input
          v-else
          v-model="tempBillNo"
          ref="billNoInput"
          style="width: 130px"
          @blur="saveBillNo"
          @keyup.enter="saveBillNo"
        />
      </div>
    </div>
    <hr />

    <!-- 第一张源单选择按钮（应收转应收和应付转应付时不显示） -->
    <div class="chooseSourceDocument" v-if="WriteoffType !== 'yszys' && WriteoffType !== 'yfzyf'">
      <el-button round @click="firstSourceDocDialog.open()" :disabled="!canSelectSourceDoc">
        <span v-if="WriteoffType === 'yscys'">选择预收单据</span>
        <span v-else-if="WriteoffType === 'yfcyf'">选择预付单据</span>
        <span v-else-if="WriteoffType === 'yscyf'">选择应收单据</span>
      </el-button>
    </div>

    <!-- 第一张表格（应收转应收和应付转应付时不显示） -->
    <div class="settlement-table" v-if="WriteoffType !== 'yszys' && WriteoffType !== 'yfzyf'">
      <el-table
        :data="
          FirestSourceDocuments.length > 0
            ? FirestSourceDocuments
            : placeholderRows
        "
        style="width: 100%"
        border
        :header-cell-style="{ 'background-color': '#f5f7fa' }"
        :cell-style="tableCellStyle"
        show-summary
        :summary-method="getSummaries"
      >
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column prop="docNo" label="源单编号" min-width="120">
          <template #default="{ row }">
            <span v-if="row.docNo" class="link-text">{{ row.docNo }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="businessType" label="业务类别" min-width="100" />
        <el-table-column prop="docDate" label="单据日期" min-width="110" />
        <el-table-column prop="docAmount" label="单据金额" min-width="100" />
        <el-table-column
          prop="writtenOffAmount"
          label="已核销金额"
          min-width="110"
        />
        <el-table-column
          prop="unwrittenOffAmount"
          label="未核销金额"
          min-width="110"
        />
        <el-table-column
          prop="currentWriteOffAmount"
          label="*本次核销金额"
          min-width="130"
        >
          <template #default="{ row }">
            <el-input
              v-model.number="row.currentWriteOffAmount"
              type="number"
              step="0.01"
              style="width: 100px"
              :max="Math.abs(row.unwrittenOffAmount)"
              @keydown="preventExceedMax($event, Math.abs(row.unwrittenOffAmount), row)"
              @change="validateWriteOffAmount(row)"
              @blur="validateWriteOffAmount(row)"
              v-if="row.docNo"
            />
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="单据备注" min-width="150" />
      </el-table>
    </div>

    <!-- 第二张源单对话框 -->
    <SourceDocDialog
      ref="secondSourceDocDialog"
      :source-doc-list="secondSourceDocs"
      @confirm="handleSecondSourceDocConfirm"
    />

    <!-- 第二张源单选择按钮和自动核销按钮 -->
    <div class="chooseSourceDocument">
      <el-button round @click="secondSourceDocDialog.open()" :disabled="!canSelectSourceDoc">
        <span v-if="WriteoffType === 'yscys'">选择应收单据</span>
        <span v-else-if="WriteoffType === 'yfcyf'">选择应付单据</span>
        <span v-else-if="WriteoffType === 'yscyf'">选择应付单据</span>
        <span v-else-if="WriteoffType === 'yszys'">选择应收单据</span>
        <span v-else-if="WriteoffType === 'yfzyf'">选择应付单据</span>
      </el-button>

      <!-- 自动核销按钮（应收转应收和应付转应付时不显示） -->
      <el-button round @click="autoWriteOff" :disabled="!canAutoWriteOff" v-if="WriteoffType !== 'yszys' && WriteoffType !== 'yfzyf'"> 
        自动核销 
      </el-button>
    </div>

    <!-- 第二张表格（始终显示） -->
    <div class="settlement-table">
      <el-table
        :data="
          SecondSourceDocuments.length > 0
            ? SecondSourceDocuments
            : placeholderRows
        "
        style="width: 100%"
        border
        :header-cell-style="{ 'background-color': '#f5f7fa' }"
        :cell-style="tableCellStyle"
        show-summary
        :summary-method="getSummaries"
      >
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column prop="docNo" label="源单编号" min-width="120">
          <template #default="{ row }">
            <span v-if="row.docNo" class="link-text">{{ row.docNo }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="businessType" label="业务类别" min-width="100" />
        <el-table-column prop="docDate" label="单据日期" min-width="110" />
        <el-table-column prop="docAmount" label="单据金额" min-width="100" />
        <el-table-column
          prop="writtenOffAmount"
          label="已核销金额"
          min-width="110"
        />
        <el-table-column
          prop="unwrittenOffAmount"
          label="未核销金额"
          min-width="110"
        />
        <el-table-column
          prop="currentWriteOffAmount"
          label="*本次核销金额"
          min-width="130"
        >
          <template #default="{ row }">
            <el-input
              v-model.number="row.currentWriteOffAmount"
              type="number"
              step="0.01"
              style="width: 100px"
              :max="Math.abs(row.unwrittenOffAmount)"
              @keydown="preventExceedMax($event, Math.abs(row.unwrittenOffAmount), row)"
              @change="validateWriteOffAmount(row)"
              @blur="validateWriteOffAmount(row)"
              v-if="row.docNo"
            />
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="单据备注" min-width="150" />
      </el-table>
    </div>

    <!-- 备注 -->
    <div class="note">
      <el-input v-model="note" :rows="2" type="textarea" placeholder="备注" />
    </div>

    <div
      style="
        display: flex;
        justify-content: right;
        align-items: center;
        margin-top: 8px;
      "
    >
      
      <div style="position: fixed; top: 150px; right: 50px; z-index: 9999; display: flex; gap: 1px;">
        <el-button type="primary" @click="addNew" style="font-size:12px">新增</el-button>
        <el-button type="primary" @click="save" style="font-size:12px" :disabled="!canSave">保存</el-button>
      </div>

      <div class="status-indicator" v-if="showStatus">
        <img
          :src="statusImageUrl"
          :alt="statusAltText"
          class="status-image"
        />
      </div>
    </div>

    <!-- 客户对话框 -->
    <CustomerDialog 
      v-model="customerDialogVisible" 
      @confirm="handleSelectCustomer" 
    />
    <!-- 供应商对话框 -->
    <SupplierDialog ref="supplierDialog" @confirm="handleSupplierConfirm" />

    <!-- 第一个源单对话框 -->
    <SourceDocDialog
      ref="firstSourceDocDialog"
      :source-doc-list="firstSourceDocs"
      @confirm="handleFirstSourceDocConfirm"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from "vue";
import { Search } from "@element-plus/icons-vue";
import CustomerDialog from "@/util/CustomerDialog.vue";
import SupplierDialog from "@/util/SupplierDialog.vue";
import { ElMessage } from "element-plus";
import SourceDocDialog from "@/util/SourceDocDialog.vue";
import dayjs from 'dayjs';
import axios from 'axios';
import { useRoute } from "vue-router";
const route = useRoute();

// 业务类型
const WriteoffType = ref("yscys");

// 客户相关（区分普通/转出/转入）
const customerForm = reactive({ customerCode: '', customerAddress: '', customerName: '', customerType: '' });
const fromCustomerForm = reactive({ customerCode: '', customerAddress: '', customerName: '', customerType: '' });
const toCustomerForm = reactive({ customerCode: '', customerAddress: '', customerName: '', customerType: '' });
const customerList = ref([]);
const customerDialogVisible = ref(false);
const currentCustomerType = ref(''); // 标记当前选择的是普通/转出/转入客户
const selectCustomer = ref(null); // 普通客户
const fromCustomer = ref(null); // 转出客户
const toCustomer = ref(null); // 转入客户

// 供应商相关（区分普通/转出/转入）
const form = reactive({ supplier_id: "", supplier_name: "", supplier_code: "" }); 
const fromSupplierForm = reactive({ supplier_id: "", supplier_name: "", supplier_code: "" });
const toSupplierForm = reactive({ supplier_id: "", supplier_name: "", supplier_code: "" });
const supplierList = ref([]);
const supplierDialog = ref(null);
const currentSupplierType = ref(''); // 标记当前选择的是普通/转出/转入供应商
const selectedSupplier = ref(null); // 普通供应商
const fromSupplier = ref(null); // 转出供应商
const toSupplier = ref(null); // 转入供应商

// 源单相关（区分第一张/第二张表）
const firstSourceDocs = ref([]); // 第一张表源单数据
const secondSourceDocs = ref([]); // 第二张表源单数据
const FirestSourceDocuments = ref([]); // 已选择的第一张表源单
const SecondSourceDocuments = ref([]); // 已选择的第二张表源单
const placeholderRows = ref(Array(5).fill({ isPlaceholder: true }));

// 定义源单对话框的引用
const firstSourceDocDialog = ref(null);
const secondSourceDocDialog = ref(null);

// 其他基础字段
const note = ref("");
const date = ref(dayjs().format('YYYY-MM-DD'));
const Firstresponsible = ref("");
const Secondresponsible = ref("");
const showStatus = ref(false);
const statusImageUrl = ref("");
const statusAltText = ref("");

// 单据编号相关
const billNo = ref("");
const tempBillNo = ref("");
const editingBillNo = ref(false);
const billNoInput = ref(null);

// 负责人数据
const responsibleOptions = ref([
  { id: "1", label: "老板" },
  { id: "2", label: "组长-老陈" },
  { id: "3", label: "采购组员-小鹏" },
  { id: "4", label: "采购组员-小亮" },
]);

// 计算是否可以选择源单（是否已选择对应客户/供应商）
const canSelectSourceDoc = computed(() => {
  switch (WriteoffType.value) {
    case 'yscys': return !!selectCustomer.value; // 预收冲应收：需选择客户
    case 'yfcyf': return !!selectedSupplier.value; // 预付冲应付：需选择供应商
    case 'yscyf': return !!selectCustomer.value && !!selectedSupplier.value; // 应收冲应付：需选择客户+供应商
    case 'yszys': return !!fromCustomer.value && !!toCustomer.value; // 应收转应收：需选择转出+转入客户
    case 'yfzyf': return !!fromSupplier.value && !!toSupplier.value; // 应付转应付：需选择转出+转入供应商
    default: return false;
  }
});

// 计算是否可以自动核销（应收转应收和应付转应付时不显示自动核销按钮）
const canAutoWriteOff = computed(() => {
  if (WriteoffType.value === 'yszys' || WriteoffType.value === 'yfzyf') {
    return false;
  }
  return FirestSourceDocuments.value.length > 0 && SecondSourceDocuments.value.length > 0;
});

// 计算是否可以保存（是否已选择源单且填写必要信息）
const canSave = computed(() => {
  return canSelectSourceDoc.value && (FirestSourceDocuments.value.length > 0 || SecondSourceDocuments.value.length > 0);
});
const editCode = computed(() => !!route.query.code);
const writeoffId = ref(null);
// 页面加载初始化
onMounted(async () => {
  await Promise.all([
    getCustomerList(),
    getSupplierList()
  ]);

  // 再处理单据逻辑
  if (editCode.value) {
    await fetchWriteoffDetail(route.query.code);
  } else {
    generateDefaultBillNo();
  }
});

// ******************************************
console.log('sdsfds',route.query.code)

// 获取核销单详情并回显
const fetchWriteoffDetail = async (writeOffCode) => {
  try {
    const response = await axios.get('/finance/getWriteoffByCode', {
      params: { 
        write_off_code: writeOffCode,
        companyCode: route.query.companyCode || 'GS0001'
      }
    });
    console.log('接受的detal', response.data)
    if (response.data.code === 5200) {
      const writeoff = response.data.writeoff;
      // 1. 基础信息回显
      writeoffId.value = writeoff.write_off_id;
      billNo.value = writeoff.write_off_code;
      tempBillNo.value = writeoff.write_off_code;
      date.value = writeoff.document_date ? dayjs(writeoff.document_date).format('YYYY-MM-DD') : '';
      note.value = writeoff.remark || '';
      WriteoffType.value = writeoff.business_type;
      // 回显业务员（如果后端返回了业务员ID）
      Firstresponsible.value = writeoff.first_responsible || '';
      Secondresponsible.value = writeoff.second_responsible || '';
      
      // 2. 根据业务类型，通过 write_off_present 和 write_off_target 从本地列表匹配客户/供应商
      switch (writeoff.business_type) {
        case 'yscys': // 预收冲应收：write_off_present = 客户编码
          customerForm.customerCode = writeoff.write_off_present || '';
          await fetchCustomerDetail(customerForm.customerCode, 'normal');
          break;
          
        case 'yfcyf': // 预付冲应付：write_off_present = 供应商编码
          form.supplier_code = writeoff.write_off_present || '';
          await fetchSupplierDetail(form.supplier_code, 'normal');
          break;
          
        case 'yscyf': // 应收冲应付：write_off_present=客户编码，write_off_target=供应商编码
          customerForm.customerCode = writeoff.write_off_present || '';
          await fetchCustomerDetail(customerForm.customerCode, 'normal');
          form.supplier_code = writeoff.write_off_target || '';
          await fetchSupplierDetail(form.supplier_code, 'normal');
          break;
          
        case 'yszys': // 应收转应收：write_off_present=转出客户编码，write_off_target=转入客户编码
          fromCustomerForm.customerCode = writeoff.write_off_present || '';
          await fetchCustomerDetail(fromCustomerForm.customerCode, 'from');
          toCustomerForm.customerCode = writeoff.write_off_target || '';
          await fetchCustomerDetail(toCustomerForm.customerCode, 'to');
          break;
          
        case 'yfzyf': // 应付转应付：write_off_present=转出供应商编码，write_off_target=转入供应商编码
          fromSupplierForm.supplier_code = writeoff.write_off_present || '';
          await fetchSupplierDetail(fromSupplierForm.supplier_code, 'from');
          toSupplierForm.supplier_code = writeoff.write_off_target || '';
          await fetchSupplierDetail(toSupplierForm.supplier_code, 'to');
          break;
      }
      
      // 3. 加载源单数据（必须先加载源单列表，才能回显已选择的源单）
      await loadSourceDocsByBusinessType();
      
      // 4. 回显已选择的源单和核销金额（从 verification1List 和 verification2List 中获取，匹配本地源单列表补充字段）
      if (writeoff.verification1List && writeoff.verification1List.length) {
        FirestSourceDocuments.value = writeoff.verification1List.map(item => {
          // 从本地源单列表中匹配对应的源单，补充完整字段
          const matchedDoc = firstSourceDocs.value.find(doc => doc.docId === item.related_id) || {};
          return {
            docId: item.related_id,
            docNo: item.source_code,
            businessType: matchedDoc.businessType || '',
            docDate: matchedDoc.docDate || '',
            docAmount: item.amount || '0.00',
            writtenOffAmount: item.written_off_amount || '0.00',
            // 未核销金额 = 单据金额 - 已核销金额
            unwrittenOffAmount: (Number(item.amount || 0) - Number(item.written_off_amount || 0)).toFixed(2),
            currentWriteOffAmount: Number(item.current_written_off_amount || 0),
            remark: matchedDoc.remark || '',
            isReturn: item.isReturn || 0,
            relatedId: matchedDoc.relatedId || '',
            relatedType: matchedDoc.relatedType || ''
          };
        });
      }
      
      if (writeoff.verification2List && writeoff.verification2List.length) {
        SecondSourceDocuments.value = writeoff.verification2List.map(item => {
          const matchedDoc = secondSourceDocs.value.find(doc => doc.docId === item.related_id) || {};
          return {
            docId: item.related_id,
            docNo: item.source_code,
            businessType: matchedDoc.businessType || '',
            docDate: matchedDoc.docDate || '',
            docAmount: item.amount || '0.00',
            writtenOffAmount: item.written_off_amount || '0.00',
            unwrittenOffAmount: (Number(item.amount || 0) - Number(item.written_off_amount || 0)).toFixed(2),
            currentWriteOffAmount: Number(item.current_written_off_amount || 0),
            remark: matchedDoc.remark || '',
            isReturn: item.isReturn || 0,
            relatedId: matchedDoc.relatedId || '',
            relatedType: matchedDoc.relatedType || ''
          };
        });
      }
    } else {
      ElMessage.error('获取核销单详情失败：' + response.data.msg);
    }
  } catch (error) {
    console.error('获取核销单详情出错：', error);
    ElMessage.error('网络错误，无法加载核销单详情');
  }
};

// 回显客户详情
const fetchCustomerDetail = async (customerCode, type = 'normal') => {
console.log('拿到的客户编号',customerCode)
  try {
    if (!customerCode || customerList.value.length === 0) {
      ElMessage.warning(type === 'normal' ? '客户编码为空或客户列表未加载' : 
                       type === 'from' ? '转出客户编码为空或客户列表未加载' : '转入客户编码为空或客户列表未加载');
      return;
    }

    const matchedCustomer = customerList.value.find(item => item.code === customerCode);
    if (!matchedCustomer) {
      ElMessage.warning(`未在客户列表中找到编码为${customerCode}的客户`);
      return;
    }

    
    const customerInfo = {
      customerCode: matchedCustomer.code,
      customerAddress: matchedCustomer.primaryContactAddress || matchedCustomer.address || '',
      customerName: matchedCustomer.name || matchedCustomer.customer_name || '',
      customerType: matchedCustomer.typeName || matchedCustomer.customer_type || '',
      id: matchedCustomer.id || matchedCustomer.customer_id || '' 
    };

    if (type === 'normal') {
      Object.assign(customerForm, customerInfo);
      selectCustomer.value = matchedCustomer; 
    } else if (type === 'from') {
      Object.assign(fromCustomerForm, customerInfo);
      fromCustomer.value = matchedCustomer;
    } else if (type === 'to') {
      Object.assign(toCustomerForm, customerInfo);
      toCustomer.value = matchedCustomer;
    }

    console.log(`匹配到的${type === 'normal' ? '客户' : type === 'from' ? '转出客户' : '转入客户'}：`, customerInfo);
  } catch (error) {
    console.error(`匹配${type === 'normal' ? '客户' : type === 'from' ? '转出客户' : '转入客户'}详情失败：`, error);
    ElMessage.error(`加载${type === 'normal' ? '客户' : type === 'from' ? '转出客户' : '转入客户'}信息失败`);
  }
};

// 回显供应商
const fetchSupplierDetail = async (supplierCode, type = 'normal') => {
  console.log('拿到的供应商编号',supplierCode)
  try {
    if (!supplierCode || supplierList.value.length === 0) {
      ElMessage.warning(type === 'normal' ? '供应商编码为空或供应商列表未加载' : 
                       type === 'from' ? '转出供应商编码为空或供应商列表未加载' : '转入供应商编码为空或供应商列表未加载');
      return;
    }

    // 
    const matchedSupplier = supplierList.value.find(item => item.code === supplierCode);
    if (!matchedSupplier) {
      ElMessage.warning(`未在供应商列表中找到编码为${supplierCode}的供应商`);
      return;
    }

    // 组装供应商信息（字段与 supplierList 返回结构一致）
    const supplierInfo = {
      supplier_id: matchedSupplier.rawData?.id || matchedSupplier.id || matchedSupplier.supplier_id || '',
      supplier_name: matchedSupplier.SupplierName || matchedSupplier.supplier_name || '',
      supplier_code: matchedSupplier.SupplierCode || matchedSupplier.supplier_code || ''
    };

    // 根据类型赋值到对应表单和状态变量
    if (type === 'normal') {
      Object.assign(form, supplierInfo);
      selectedSupplier.value = matchedSupplier; 
    } else if (type === 'from') {
      Object.assign(fromSupplierForm, supplierInfo);
      fromSupplier.value = matchedSupplier;
    } else if (type === 'to') {
      Object.assign(toSupplierForm, supplierInfo);
      toSupplier.value = matchedSupplier;
    }

    console.log(`匹配到的${type === 'normal' ? '供应商' : type === 'from' ? '转出供应商' : '转入供应商'}：`, supplierInfo);
  } catch (error) {
    console.error(`匹配${type === 'normal' ? '供应商' : type === 'from' ? '转出供应商' : '转入供应商'}详情失败：`, error);
    ElMessage.error(`加载${type === 'normal' ? '供应商' : type === 'from' ? '转出供应商' : '转入供应商'}信息失败`);
  }
};
// ******************************************


// 生成默认单据编号
const generateDefaultBillNo = async () => {
  try {
    const response = await axios.get("/finance/getNextWriteoffNo");
    if (response.data.code === 5200) {
      billNo.value = response.data.billNo;
      tempBillNo.value = billNo.value;
    } else {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0");
      const day = String(now.getDate()).padStart(2, "0");
      billNo.value = `HXD${year}${month}${day}01`;
      tempBillNo.value = billNo.value;
    }
  } catch (error) {
    console.error("获取单据编号失败：", error);
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, "0");
    const day = String(now.getDate()).padStart(2, "0");
    billNo.value = `HXD${year}${month}${day}01`;
    tempBillNo.value = billNo.value;
  }
};

// 客户相关方法
const openCustomerDialog = (type = 'normal') => {
  currentCustomerType.value = type;
  customerDialogVisible.value = true;
};
const getCustomerList = async () => {
  try {
    const response = await axios.get("/finance/customerPage", { params: { pageNum: 1, pageSize: 100 } });
    if (response.data.code === 5200) {
      customerList.value = response.data.customerList;
      console.log('接口返回的customerList',customerList.value)
    } else {
      ElMessage.error("获取客户失败：" + response.data.msg);
    }
  } catch (error) {
    console.error("获取客户出错：", error);
    ElMessage.error("网络错误，无法获取客户数据");
  }
};
const handleSelectCustomer = (customers) => {
  if (customers && customers.length > 0) {
    const customer = customers[0];
    const customerInfo = {
      customerCode: customer.code, 
      customerAddress: customer.primaryContactAddress || '', 
      customerName: customer.name, 
      customerType: customer.typeName 
    };
    console.log('当前客户类型',currentSupplierType.value);
    if (currentCustomerType.value === 'to' && WriteoffType.value === 'yszys') {
      if (fromCustomer.value && customer.code === fromCustomer.value.code) {
        ElMessage.error("转入客户不能与转出客户相同，请重新选择");
        customerDialogVisible.value = false;
        return; 
      }
    }
    // 根据当前客户类型赋值
    switch (currentCustomerType.value) {
      case 'normal':
        selectCustomer.value = customer; 
        Object.assign(customerForm, customerInfo); 
        break;
      case 'from':
        fromCustomer.value = customer;
        Object.assign(fromCustomerForm, customerInfo);
        break;
      case 'to':
        toCustomer.value = customer;
        Object.assign(toCustomerForm, customerInfo);
        break;
      default:
        selectCustomer.value = customer; 
        Object.assign(customerForm, customerInfo); 
        console.warn("未匹配的客户类型：", currentCustomerType.value);
    }
    console.log('选中的customerForm',customerForm)
    loadSourceDocsByBusinessType();
  }
  customerDialogVisible.value = false;
};

// 供应商相关方法
const openSupplierDialog = (type = 'normal') => {
  currentSupplierType.value = type;
  supplierDialog.value.open();
};
const getSupplierList = async () => {
  try {
    const response = await axios.get("/finance/getSupplierList", { 
      params:{pageNum:1,pageSize:100}
    });
    console.log('拿到的供应商数据',response.data.supplierList.pageInfo.list)
    if (response.data.code === 5200) {
      supplierList.value = response.data.supplierList.pageInfo.list;
    } else {
      ElMessage.error("获取供应商失败：" + response.data.msg);
    }
  } catch (error) {
    console.error("获取供应商出错：", error);
    ElMessage.error("网络错误，无法获取供应商数据");
  }
};

const handleSupplierConfirm = (supplier) => {
  console.log('子组件传递的供应商数据：', supplier);
  if (!supplier || !supplier.rawData) {
    ElMessage.warning("请选择有效的供应商");
    return;
  }

  const supplierInfo = {
    supplier_id: supplier.rawData.id,
    supplier_name: supplier.SupplierName || '',
    supplier_code: supplier.SupplierCode || ''
  };
  if (currentSupplierType.value === 'to' && WriteoffType.value === 'yfzyf') {
    if (fromSupplier.value && supplier.SupplierCode === fromSupplier.value.SupplierCode) {
      ElMessage.error("转入供应商不能与转出供应商相同，请重新选择");
      return; 
    }
  }
  switch (currentSupplierType.value) {
    case 'normal':
      selectedSupplier.value = supplier; 
      Object.assign(form, supplierInfo); 
      break;
    case 'from':
      fromSupplier.value = supplier; 
      Object.assign(fromSupplierForm, supplierInfo);
      break;
    case 'to':
      toSupplier.value = supplier; 
      Object.assign(toSupplierForm, supplierInfo);
      break;
    default:
      selectedSupplier.value = supplier;
      Object.assign(form, supplierInfo);
      console.warn("未匹配的供应商类型：", currentSupplierType.value);
  }
  console.log('赋值后的表单数据：', form);
  loadSourceDocsByBusinessType();
};

/**
 * 业务类型 -> 源单类型映射
 */
const loadSourceDocsByBusinessType = async () => {
  try {
    console.log('接受的业务类型',WriteoffType.value)
    switch (WriteoffType.value) {
      // 1. 预收冲应收（客户：预收单 + 应收单）
      case 'yscys':
        if (selectCustomer.value) {
          // 第一张表：预收单（付款单）
          const advanceRes = await axios.get('/finance/getReceiptData', {
            params: { companyCode:'GS0001',customer_id: selectCustomer.value.id }
          });
          console.log('预收单',advanceRes.data.receiptData)
          // 第二张表：应收单（销售单）
          const receivableRes = await axios.get('/finance/getSaleSlipByCustomerCode', {
            params: { customer_code: selectCustomer.value.code }
          });
          console.log('应收单',receivableRes.data.saleSlipList.salesSlipList)
          if (advanceRes.data.code === 5200) {
            firstSourceDocs.value = formatSourceDocs(advanceRes.data.receiptData, '收款');
          }
          if (receivableRes.data.code === 5200) {
            secondSourceDocs.value = formatSourceDocs(receivableRes.data.saleSlipList.salesSlipList, 'receipt');
          }
        }
        break;

      // 2. 预付冲应付（供应商：预付单 + 应付单）
      case 'yfcyf':
        if (selectedSupplier.value) {
          // 第一张表：预付单（付款单）
          const prepayRes = await axios.get('/finance/getPaymentData', {
             params: { companyCode:'GS0001',supplier_id: selectedSupplier.value.rawData.id }
          });
          console.log('预付单',prepayRes.data.paymentData)

          // 第二张表：应付单（采购单）
          const payableRes = await axios.get('/finance/getProcumentList', {
            params: { pageNum:1,pageSize:10,companyCode:'CNY001',supplier_code: selectedSupplier.value.SupplierCode }
          });
          console.log('应付单',payableRes.data.procurementPageInfo.list)

          if (prepayRes.data.code === 5200) {
            firstSourceDocs.value = formatSourceDocs(prepayRes.data.paymentData, '付款');
          }
          if (payableRes.data.code === '5200') {
            secondSourceDocs.value = formatSourceDocs(payableRes.data.procurementPageInfo.list, 'payment');
          }
        }
        break;

      // 3. 应收冲应付（客户应收单 + 供应商应付单）
      case 'yscyf':
        if (selectCustomer.value && selectedSupplier.value) {
          // 第一张表：客户应收单
          const receivableRes = await axios.get('/finance/getSaleSlipByCustomerCode', {
            params: { customer_code: selectCustomer.value.code }
          });
          console.log('应收单',receivableRes.data.saleSlipList.salesSlipList)

          // 第二张表：供应商应付单
          const payableRes = await axios.get('/finance/getProcumentList', {
            params: { pageNum:1,pageSize:10,companyCode:'CNY001',supplier_code: selectedSupplier.value.Supplier_code }
          });
          console.log('应付单',payableRes.data.procurementPageInfo.list)

          if (receivableRes.data.code === 5200) {
            firstSourceDocs.value = formatSourceDocs(receivableRes.data.saleSlipList.salesSlipList, 'receipt');
          }
          if (payableRes.data.code === '5200') {
            secondSourceDocs.value = formatSourceDocs(payableRes.data.procurementPageInfo.list, 'payment');
          }
        }
        break;

      // 4. 应收转应收（转出客户应收单）
      case 'yszys':
        if (fromCustomer.value) {
          // 第二张表：转出客户应收单
          const receivableRes = await axios.get('/finance/getSaleSlipByCustomerCode', {
            params: { customer_code: fromCustomer.value.code }
          });
          console.log('应收单',receivableRes.data.saleSlipList.salesSlipList)

          if (receivableRes.data.code === 5200) {
            secondSourceDocs.value = formatSourceDocs(receivableRes.data.saleSlipList.salesSlipList, 'receipt');
          }
        }
        break;

      // 5. 应付转应付（转出供应商应付单）
      case 'yfzyf':
        if (fromSupplier.value) {
          // 第二张表：转出供应商应付单
          const payableRes = await axios.get('/finance/getProcumentList', {
            params: { pageNum:1,pageSize:10,companyCode:'CNY001',supplier_code: fromSupplier.value.SupplierCode }
          });
          console.log('应付单',payableRes.data.procurementPageInfo.list)

          if (payableRes.data.code === '5200') {
            secondSourceDocs.value = formatSourceDocs(payableRes.data.procurementPageInfo.list, 'payment');
          }
        }
        break;
    }
  } catch (error) {
    console.error("加载源单失败：", error);
    ElMessage.error("网络错误，无法加载源单数据");
  }
};

/**
 * 格式化源单数据（统一结构）
 */
const formatSourceDocs = (docs, bizType) => {
  if (!Array.isArray(docs)) docs = [docs];
  console.log('docs', docs);
  return docs.map(doc => {
    let finalBizType = bizType; // 先保留原始bizType
    const isRefundDoc = Number(doc.isReturn) === 1 || Number(doc.isRefund) === 1;

    // 按原始bizType分类处理，避免覆盖预收/预付类型
    switch (bizType) {
      // 1. 预收单（原始bizType=收款）- 保持类型不变，仅处理退货标识
      case '收款':
        finalBizType = '收款'; // 强制保留预收单类型
        break;
      // 2. 预付单（原始bizType=付款）- 保持类型不变，仅处理退货标识
      case '付款':
        finalBizType = '付款'; // 强制保留预付单类型
        break;
      // 3. 销售相关（原始bizType=receipt）- 区分普通销货/销货退货
      case 'receipt':
        finalBizType = isRefundDoc ? '销货退货' : '普通销货';
        break;
      // 4. 采购相关（原始bizType=payment）- 区分普通采购/采购退货
      case 'payment':
        finalBizType = isRefundDoc ? '采购退货' : '普通采购';
        break;
      // 其他情况保留原始类型
      default:
        finalBizType = bizType;
    }

    // 计算基础金额（退货单据转为负数）
    const baseDocAmount = Number(doc.amount || doc.slipPrice || doc.procurement_amount || 0);
    const baseWrittenOffAmount = Number(doc.written_off_amount || 0);
    
    // 退货单据：金额转为负数（仅销售/采购退货，预收/预付退货也适用）
    const docAmount = isRefundDoc ? -baseDocAmount : baseDocAmount;
    const writtenOffAmount = isRefundDoc ? -baseWrittenOffAmount : baseWrittenOffAmount;
    // const thisPayment = isRefundDoc ? -doc.thisPayment || 0 : doc.thisPayment || 0;
    // const pay_amount = isRefundDoc ? -doc.pay_amount || 0 : doc.pay_amount || 0;

    return {
      docId: doc.receipt_id || doc.payment_id || doc.id || doc.procurement_id,
      docNo: doc.code || doc.receipt_code || doc.returnCode || doc.payment_code || doc.procurement_code,
      businessType: finalBizType, // 最终业务类别（保留预收/预付）
      isReturn: Number(doc.isReturn) || Number(doc.isRefund) || 0, // 统一退货标记（1=退货）
      docDate: doc.date || doc.receipt_date || doc.payment_date || doc.procurement_date,
      company_code: doc.company_code || doc.companyCode,
      slipPrice: docAmount.toFixed(2), // 同步负数（原slipPrice与docAmount一致）
      docAmount: docAmount.toFixed(2), // 退货单据为负数
      writtenOffAmount: (writtenOffAmount).toFixed(2), // 退货单据为负数
      get unwrittenOffAmount() {
        const docAmount = this.docAmount;
        // 未核销金额 = 单据金额 - 已核销金额（保持逻辑一致）
        return (Number(docAmount) - Number(this.writtenOffAmount)).toFixed(2);
      },
      remark: doc.remark || doc.remarks || "",
      relatedId: doc.customer_id || doc.supplier_id,
      relatedType: doc.customer_id ? 'customer' : 'supplier'
    };
  });
};

// 源单选择确认
const handleFirstSourceDocConfirm = (docs) => {
  const existingIds = new Set(FirestSourceDocuments.value.map(doc => doc.docId));
  const newDocs = docs.filter(doc => !existingIds.has(doc.docId));
  if (newDocs.length === 0) {
    ElMessage.warning("所选单据已添加，不能重复选择");
    return;
  }
  FirestSourceDocuments.value = [
    ...FirestSourceDocuments.value,
    ...newDocs.map(doc => ({ ...doc, currentWriteOffAmount: 0 }))
  ];
  console.log('FirestSourceDocuments', FirestSourceDocuments.value);
};

const handleSecondSourceDocConfirm = (docs) => {
  const existingIds = new Set(SecondSourceDocuments.value.map(doc => doc.docId));
  const newDocs = docs.filter(doc => !existingIds.has(doc.docId));

  if (newDocs.length === 0) {
    ElMessage.warning("所选单据已添加，不能重复选择");
    return;
  }
  SecondSourceDocuments.value = [
    ...SecondSourceDocuments.value,
    ...newDocs.map(doc => ({ ...doc, currentWriteOffAmount: 0 }))
  ];
  console.log('SecondSourceDocuments', SecondSourceDocuments.value);
};

// 计算两个表的本次核销总额
const firstTotalWriteOff = computed(() => {
  return FirestSourceDocuments.value.reduce((sum, row) => sum + Number(row.currentWriteOffAmount || 0), 0);
});
const secondTotalWriteOff = computed(() => {
  return SecondSourceDocuments.value.reduce((sum, row) => sum + Number(row.currentWriteOffAmount || 0), 0);
});

// 自动核销（应收转应收和应付转应付时不显示此功能）
const autoWriteOff = () => {
  if (FirestSourceDocuments.value.length === 0 || SecondSourceDocuments.value.length === 0) {
    ElMessage.warning("请先选择两张表的源单据");
    return;
  }

  // 计算两张表的未核销总额（取绝对值判断大小，避免负数影响）
  const firstUnwrittenTotal = Math.abs(FirestSourceDocuments.value.reduce((sum, doc) => sum + Number(doc.unwrittenOffAmount), 0));
  const secondUnwrittenTotal = Math.abs(SecondSourceDocuments.value.reduce((sum, doc) => sum + Number(doc.unwrittenOffAmount), 0));

  // 确定较小总额表和较大总额（基于绝对值）
  const [smallerTable, largerTable] = firstUnwrittenTotal <= secondUnwrittenTotal 
    ? [FirestSourceDocuments, SecondSourceDocuments]
    : [SecondSourceDocuments, FirestSourceDocuments];

  // 计算较大总额表的自身总额（取绝对值）
  const largerTableTotal = Math.abs(largerTable.value.reduce((sum, doc) => sum + Number(doc.unwrittenOffAmount), 0));
  smallerTable.value.forEach(doc => {
    // 可分配金额 = 未核销金额（保留原符号），但不能超过单据金额绝对值
    const maxAllocable = Number(doc.unwrittenOffAmount);
    const docAmountAbs = Math.abs(Number(doc.docAmount)); // 单据金额绝对值（上限）
    // 取未核销金额和单据金额绝对值的较小值（保留原符号）
    const finalAmount = Math.abs(maxAllocable) > docAmountAbs 
      ? docAmountAbs * Math.sign(maxAllocable) 
      : maxAllocable;
    doc.currentWriteOffAmount = finalAmount;
  });

  // 计算需要分配给较大总额表的总金额（取绝对值，再按原符号分配）
  const totalToAllocateAbs = Math.abs(smallerTable.value.reduce((sum, doc) => sum + Number(doc.currentWriteOffAmount), 0));
  const totalToAllocateSign = totalToAllocateAbs > 0 ? Math.sign(smallerTable.value[0].unwrittenOffAmount) : 1;
  const totalToAllocate = totalToAllocateAbs * totalToAllocateSign;
  let remaining = totalToAllocate; // 剩余未分配金额
  largerTable.value.forEach((doc, index) => {
    if (largerTableTotal === 0) {
      doc.currentWriteOffAmount = 0;
      return;
    }

    // 按绝对值计算比例，再还原符号
    const docUnwrittenAbs = Math.abs(Number(doc.unwrittenOffAmount));
    const ratio = docUnwrittenAbs / largerTableTotal;
    const allocateAmountAbs = Math.round(totalToAllocateAbs * ratio * 100) / 100;
    // 计算理论分配金额（保留原符号）
    let allocateAmount = allocateAmountAbs * Math.sign(doc.unwrittenOffAmount);

    // 关键校验：分配金额不能超过单据金额绝对值（保留原符号）
    const docAmountAbs = Math.abs(Number(doc.docAmount));
    if (Math.abs(allocateAmount) > docAmountAbs) {
      allocateAmount = docAmountAbs * Math.sign(allocateAmount);
    }

    // 最后一条分摊剩余金额（同样需要校验单据金额上限）
    if (index === largerTable.value.length - 1) {
      // 剩余金额也不能超过当前单据的金额上限
      const maxRemaining = docAmountAbs * Math.sign(remaining);
      doc.currentWriteOffAmount = Math.abs(remaining) > docAmountAbs 
        ? maxRemaining 
        : remaining;
    } else {
      doc.currentWriteOffAmount = allocateAmount;
      remaining -= allocateAmount;
    }

    // 最终二次校验：确保不超过未核销金额（双重保险）
    if (Math.abs(doc.currentWriteOffAmount) > docUnwrittenAbs) {
      doc.currentWriteOffAmount = docUnwrittenAbs * Math.sign(doc.currentWriteOffAmount);
      remaining += allocateAmount - doc.currentWriteOffAmount; // 调整剩余金额
    }
  });
  ElMessage.success("自动核销完成");
};

// 核销金额验证
const validateWriteOffAmount = (row) => {
  const unwritten = Math.abs(Number(row.unwrittenOffAmount)); // 未核销金额（绝对值）
  const docAmountAbs = Math.abs(Number(row.docAmount)); // 单据总金额（绝对值，适配负数）
  const current = Number(row.currentWriteOffAmount); // 本次核销金额（保留正负）
  
  // 校验金额不超过单据总金额（取绝对值比较，适配负数）
  if (Math.abs(current) > docAmountAbs) {
    // 重置为单据总金额（保留原正负号，确保退货/冲销单据仍为负数）
    row.currentWriteOffAmount = Number(row.docAmount) * (current < 0 ? -1 : 1);
    ElMessage.warning(`本次核销金额不能超过单据总金额${docAmountAbs.toFixed(2)}`);
    return; // 触发第一个校验后直接返回，避免重复提示
  }

  // 校验金额不超过未核销金额（取绝对值比较）
  if (Math.abs(current) > unwritten) {
    row.currentWriteOffAmount = Number(row.unwrittenOffAmount) * (current < 0 ? -1 : 1); // 保持正负号一致
    ElMessage.warning(`本次核销金额不能超过未核销金额${unwritten.toFixed(2)}`);
    return;
  }
  
  // 允许负数的单据类型：销货退货、采购退货、收款（预收单）、付款（预付单）
  const allowNegativeTypes = ['销货退货', '采购退货', '收款', '付款'];
  // 非允许类型的单据不允许负数
  if (current < 0 && !allowNegativeTypes.includes(row.businessType)) {
    row.currentWriteOffAmount = 0;
    ElMessage.warning("该类型单据不能输入负数");
  }
};

// 防止输入超过最大值（支持退货单据、预收单、预付单负数输入）
const preventExceedMax = (event, max, row) => { // row 参数，用于判断是否为允许负数的单据
  if (event.key === "e" || event.key === "E") event.preventDefault();
  
  // 允许输入负号的单据类型：销货退货、采购退货、收款（预收单）、付款（预付单）
  const allowMinusTypes = ['销货退货', '采购退货', '收款', '付款'];
  // 允许类型的单据可输入负号
  if (event.key === "-" && allowMinusTypes.includes(row.businessType)) {
    return; // 不阻止负号输入
  }
  
  // 非允许类型的单据阻止负数输入
  if (event.key === "-" && !allowMinusTypes.includes(row.businessType)) {
    event.preventDefault();
    ElMessage.warning("该类型单据不能输入负数");
    return;
  }
  
  // 校验输入值不超过最大值（取绝对值比较）
  const newValue = event.target.value + event.key;
  if (newValue && Math.abs(Number(newValue)) > max) {
    event.preventDefault();
    ElMessage.warning(`输入值不能超过${max}`);
  }
};

// 表格合计计算
const getSummaries = ({ columns, data }) => {
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 1) {
      sums[index] = "合计";
      return;
    }
    const field = column.property;
    if (["docAmount", "writtenOffAmount", "unwrittenOffAmount", "currentWriteOffAmount"].includes(field)) {
      // 直接累加（包含负数），保留2位小数
      const values = data.map(item => Number(item[field]) || 0);
      const sum = values.reduce((prev, curr) => prev + curr, 0);
      sums[index] = sum.toFixed(2);
    } else {
      sums[index] = "";
    }
  });
  return sums;
};

// 业务类型变化时重置
const handleWriteoffTypeChange = () => {
  // 重置源单数据
  firstSourceDocs.value = [];
  secondSourceDocs.value = [];
  FirestSourceDocuments.value = [];
  SecondSourceDocuments.value = [];
  // 重置客户/供应商数据
  Object.keys(customerForm).forEach(key => customerForm[key] = '');
  Object.keys(fromCustomerForm).forEach(key => fromCustomerForm[key] = '');
  Object.keys(toCustomerForm).forEach(key => toCustomerForm[key] = '');
  Object.keys(form).forEach(key => form[key] = '');
  Object.keys(fromSupplierForm).forEach(key => fromSupplierForm[key] = '');
  Object.keys(toSupplierForm).forEach(key => toSupplierForm[key] = '');
  selectCustomer.value = null;
  fromCustomer.value = null;
  toCustomer.value = null;
  selectedSupplier.value = null;
  fromSupplier.value = null;
  toSupplier.value = null;
  // 重置其他状态
  showStatus.value = false;
  note.value = "";
  generateDefaultBillNo();
};

// 保存核销单
const save = async () => {
  try {
    if (WriteoffType.value === 'yszys') {
      // 应收转应收：转入客户 ≠ 转出客户
      if (fromCustomerForm.customerCode === toCustomerForm.customerCode) {
        ElMessage.error("应收转应收时，转入客户不能与转出客户相同");
        return;
      }
    } else if (WriteoffType.value === 'yfzyf') {
      // 应付转应付：转入供应商 ≠ 转出供应商
      if (fromSupplierForm.supplier_code === toSupplierForm.supplier_code) {
        ElMessage.error("应付转应付时，转入供应商不能与转出供应商相同");
        return;
      }
    }
    // 仅当需要双表核销时才校验总额相等
    const total1 = parseFloat(firstTotalWriteOff.value.toFixed(2));
    const total2 = parseFloat(secondTotalWriteOff.value.toFixed(2));

    let current_written_off_amount;

    if (['yscys', 'yfcyf', 'yscyf'].includes(WriteoffType.value)) {
      // 双表核销：金额必须相等
      if (Math.abs(total1 - total2) > 0.01) {
        ElMessage.error('两张表的本次核销金额必须相等！');
        return;
      }
      if (total1 === 0) {
        ElMessage.warning('请至少填写一笔核销金额');
        return;
      }
      current_written_off_amount = total1;
    } else {
      // 单表核销：应收转应收 / 应付转应付
      current_written_off_amount = total2; // 注意：这里改为使用第二张表的金额
      if (current_written_off_amount === 0) {
        ElMessage.warning('请至少填写一笔核销金额');
        return;
      }
    }
    
    // 1. 基础数据组装
    const saveData = {
      write_off_id: editCode.value ? writeoffId.value : null,
      write_off_code: billNo.value,
      business_type: WriteoffType.value,
      write_off_present: '',
      write_off_target: '',
      company_code:'GS0001',
      current_written_off_all_amount: current_written_off_amount,
    };
    
    // 组装转出/转入主体
    if (WriteoffType.value === 'yszys') {
      saveData.write_off_present = fromCustomerForm.customerCode;
      saveData.write_off_target = toCustomerForm.customerCode;
    } else if (WriteoffType.value === 'yfzyf') {
      saveData.write_off_present = fromSupplierForm.supplier_code;
      saveData.write_off_target = toSupplierForm.supplier_code;
    } else if (WriteoffType.value === 'yscys') {
      saveData.write_off_present = customerForm.customerCode;
      saveData.write_off_target = null; 
    } else if (WriteoffType.value === 'yfcyf') {
      saveData.write_off_present = form.supplier_code;
      saveData.write_off_target = null;
    } else if (WriteoffType.value === 'yscyf') {
      saveData.write_off_present = customerForm.customerCode;
      saveData.write_off_target = form.supplier_code;
    }

    // 付款/收款明细
    saveData.verification1List = []; // 预收、预付单
    saveData.verification2List = []; // 应收、应付单

    // 第一张表数据（应收转应收和应付转应付时为空）
    FirestSourceDocuments.value.forEach( doc=> {
      if (doc.currentWriteOffAmount !== 0) {
        saveData.verification1List.push({
          bussiness_type: WriteoffType.value === 'yfcyf' ? 'payment' : WriteoffType.value === 'yscys' ? 'receipt' : WriteoffType.value === 'yscyf' ? 'receipt' : null,
          current_written_off_amount: doc.currentWriteOffAmount,
          written_off_amount: (doc.unwrittenOffAmount - doc.currentWriteOffAmount).toFixed(2),
          amount: doc.docAmount,
          write_off_code: billNo.value,
          related_id: doc.docId,
          source_code: doc.docNo,
          isReturn: doc.isReturn || 0,
          company_code: 'GS0001',
        })
      }
    })

    // 第二张表数据
    SecondSourceDocuments.value.forEach(doc => {
      if (doc.currentWriteOffAmount !== 0) {
        saveData.verification2List.push({
          source_code: doc.docNo,
          write_off_code: billNo.value,
          related_id: doc.docId,
          bussiness_type: ['yscys', 'yszys'].includes(WriteoffType.value) ? 'receipt' : 'payment',
          amount: doc.docAmount,
          company_code:'GS0001',
          current_written_off_amount: doc.currentWriteOffAmount,
          written_off_amount: (doc.unwrittenOffAmount - doc.currentWriteOffAmount).toFixed(2),
          isReturn: doc.isReturn || 0
        });
      }
    });

    console.log('保存的saveData',saveData)
    const response = await axios.post('/finance/addWriteoff', saveData);
    if (response.data.code === 5200) {
      ElMessage.success("核销单保存成功");
    } else {
      ElMessage.error("保存失败：" + response.data.msg);
    }
  } catch (error) {
    console.error("保存核销单出错：", error);
    ElMessage.error("网络错误，保存失败");
  }
};

// 新增核销单
const addNew = () => {
  handleWriteoffTypeChange();
  ElMessage.success("已重置为新增状态");
};

// 表格样式
const tableCellStyle = ({ row }) => {
  if (row.isTotalRow) {
    return { "background-color": "#fff3cd", "font-weight": "bold" };
  }
  return {};
};
</script>

<style scoped>
.bills {
  position: relative;
  background: #ffffff;
  border: 1px solid #cfcfcf;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
  padding: 10px 20px 10px 20px;
}
.label_input {
  margin-right: 10px;
}
.searchDiv {
  display: inline-block;
  margin-right: 15px;
  margin-top: 10px;
}
.el-table .selected-row {
  --el-table-tr-bg-color: var(--el-color-primary-light-9);
  background-color: var(--el-table-tr-bg-color);
}
.bill-no {
  cursor: pointer;
  padding: 0 5px;
  border-radius: 4px;
  transition: all 0.3s;
}
.bill-no:hover {
  background-color: #f5f5f5;
  text-decoration: underline;
}
.settlement-table {
  margin-top: 20px;
}
.el-table .cell {
  padding: 8px 12px;
}
:deep(.el-table) .el-table__footer .el-table__cell {
  background-color: #fff3cd !important;
  font-weight: bold !important;
}
.note {
  margin-top: 7px;
}
.chooseSourceDocument {
  display: flex;
  justify-content: right;
  margin-top: 10px;
  margin-bottom: 10px;
}
.status-indicator {
  position: absolute;
  right: 50px;
  bottom: 100px;
  z-index: 9999;
  border-radius: 4px;
  overflow: hidden;
}
.status-image {
  width: 120px;
  height: 120px;
  display: block;
}
:deep(.el-table .el-table__row:hover > td) {
  background-color: #fff4bf !important;
}
</style>